<?php


namespace app\middleware;

use app\model\AdminAuthGroup;
use app\model\AdminAuthGroupAccess;
use app\model\AdminAuthRule;
use app\util\ReturnCode;
use app\util\Tools;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;

class AdminPermission implements MiddlewareInterface
{

    /**
     * 用户权限检测
     * @param Request $request
     * @param callable $next
     * @return Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function process(Request $request, callable $next): Response
    {
        $controller_data = explode("\\", $request->controller);
        $url = $controller_data[3];
        $action = $request->action;
        $app = $request->app;
        $url_action = $app . "/" . $url . "/" . $action;
        $ApiAuth = $request->header('Api-Auth');
        if(empty($ApiAuth)){
            return json([
                'code' => ReturnCode::INVALID,
                'msg' => '非常抱歉，您没有登录！',
                'data' => []
            ]);
        }
        $userInfo = cache('Login' . $ApiAuth);
        $userInfo_data = json_decode($userInfo, true);

        // rule里包含了rule(路由规则), ruoter(完整路由)
        if (!$this->checkAuth($userInfo_data['id'], $url_action)) {
            return json([
                'code' => ReturnCode::INVALID,
                'msg' => '非常抱歉，您没有权限这么做！',
                'data' => []
            ]);
        }

        return $next($request);
    }

    /**
     * 检测用户权限
     * @param $uid
     * @param $route
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private function checkAuth($uid, $route)
    {
        $isSupper = Tools::isAdministrator($uid);
        if (!$isSupper) {
            $rules = $this->getAuth($uid);

            return in_array($route, $rules);
        } else {
            return true;
        }
    }

    /**
     * 根据用户ID获取全部权限节点
     * @param $uid
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private function getAuth($uid)
    {
        $groups = (new AdminAuthGroupAccess())->where('uid', $uid)->find();
        if (isset($groups) && $groups->group_id) {
            $openGroup = (new AdminAuthGroup())->whereIn('id', $groups->group_id)->where(['status' => 1])->select();
            if (isset($openGroup)) {
                $openGroupArr = [];
                foreach ($openGroup as $group) {
                    $openGroupArr[] = $group->id;
                }
                $allRules = (new AdminAuthRule())->whereIn('group_id', $openGroupArr)->select();
                if (isset($allRules)) {
                    $rules = [];
                    foreach ($allRules as $rule) {
                        $rules[] = $rule->url;
                    }
                    $rules = array_unique($rules);

                    return $rules;
                } else {
                    return [];
                }
            } else {
                return [];
            }
        } else {
            return [];
        }
    }
}
